package com.kly.chatter.api.application.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class DateWeekUtils {
    /**
     * 获取当前周的所有日期
     * @param n -1代表上一周 +1代表下一周
     * @param myDate 当前日期
     */
    public static List<Date> getweek(int n, Date myDate) {
        List<Date> date = new ArrayList<Date>();
        try {
            Calendar calendar = Calendar.getInstance();
            calendar.setFirstDayOfWeek(Calendar.MONDAY);
            Calendar cal = Calendar.getInstance();
            cal.setTime(myDate);
            //判断要计算的日期是否是周日，如果是则减一天计算周六的，否则会出问题，计算到下一周了
            int dayWeek = cal.get(Calendar.DAY_OF_WEEK);//获得当前日期是一个星期的第几天
            if (1 == dayWeek) {
                cal.add(Calendar.DAY_OF_MONTH, -1);
            }
            //设置一个星期的第一天，按中国的习惯一个星期的第一天是星期一
            cal.setFirstDayOfWeek(Calendar.MONDAY);
            //获得当前日期是一个星期的第几天
            int day = cal.get(Calendar.DAY_OF_WEEK);
            //根据日历的规则，给当前日期减去星期几与一个星期第一天的差值
            cal.add(Calendar.DATE, (cal.getFirstDayOfWeek() - day + 7 * n));
            date.add(cal.getTime());
            for (int i = 1; i < 7; i++) {
                cal.add(Calendar.DATE, 1);
                date.add(cal.getTime());
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return date;
    }

    public static Date currentWeekMonday() {
        Calendar cal = Calendar.getInstance();
        int dayWeek = cal.get(Calendar.DAY_OF_WEEK);// 获得当前日期是一个星期的第几天
        if (Calendar.SUNDAY == dayWeek) {
            cal.add(Calendar.DAY_OF_MONTH, -1);//星期天向前减一天即得到上一周
        }
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        return cal.getTime();
    }

    /**
     * 加天数
     * @param date
     * @param amount
     * @return
     */
    public static Date addDay(Date date, int amount) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_YEAR, amount);
        return calendar.getTime();
    }


    /**
     * 距离当前时间几天
     * @param beginDate
     * @return
     * @throws ParseException
     */
    public static Long betweenDays(String beginDate) throws ParseException {
        long now = new Date().getTime();
        long old = new SimpleDateFormat("yyyyMMdd").parse(beginDate).getTime();
        return (now - old) / 24 / 60 / 60 / 1000;
    }

}
